package com.gssbh.framework.toolkit.mybatis;

import com.gssbh.framework.toolkit.ex.SystemException;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class NumberGeneratorIdUtils {

    static String updateSQL = "update `toolkit`.`t_number_generator` set version = version + 1 where id = ? and version = ?";

    static String querySQL = "select version from `toolkit`.`t_number_generator`  where id = ?";

    public static Long getNext(String id, DataSource dataSource) {
        try {
            return itrNext(id, dataSource.getConnection());
        } catch (Exception e) {
            // todo
            e.printStackTrace();
            throw new RuntimeException("can't get id");
        }
    }

    private static Long itrNext(String numberGeneratorId, Connection connection) throws Exception {
        connection.setAutoCommit(false);
        PreparedStatement prepared = connection.prepareStatement(querySQL);
        prepared.setString(1, numberGeneratorId);
        ResultSet resultSet = prepared.executeQuery();
        boolean hasNext = resultSet.next();
        if (!hasNext) {
//            throw new SystemException("在表中未配置该ID:" + numberGeneratorId + ", 请先配置");
        }
        long currentVersion = resultSet.getLong(1);


        prepared = connection.prepareStatement(updateSQL);
        prepared.setString(1, numberGeneratorId);
        prepared.setLong(2, currentVersion);
        int result = prepared.executeUpdate();
        if (result == 1) {
            try {
                return currentVersion + 1;
            } finally {
                connection.commit();
                connection.close();
            }
        }
        return itrNext(numberGeneratorId, connection);
    }

}
